import 'package:flutter/material.dart';
import 'package:hello_flutter/base/index.dart';

class AnimatedListWidget extends BasePage {
  const AnimatedListWidget({super.key});

  @override
  String getPageTitle() => 'AnimatedList';

  @override
  Widget buildBody(BuildContext context) => _AnimatedListWidgetRoute();
}

class _AnimatedListWidgetRoute extends StatefulWidget {
  @override
  State<_AnimatedListWidgetRoute> createState() =>
      _AnimatedListWidgetRouteState();
}

class _AnimatedListWidgetRouteState extends State<_AnimatedListWidgetRoute> {
  List<String> data = [];
  int counter = 25;

  final globalKey = GlobalKey<AnimatedListState>();
  final controller = ScrollController();

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < counter; i++) {
      data.add('${i + 1}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: AlignmentDirectional.center,
      children: [
        AnimatedList(
          key: globalKey,
          initialItemCount: data.length,
          controller: controller,
          itemBuilder: (context, index, animation) {
            return FadeTransition(
              opacity: animation,
              child: buildItem(context, index),
            );
          },
        ),
        buildAddBtn(),
      ],
    );
  }

  Widget buildAddBtn() {
    return Positioned(
      bottom: 30,
      child: FloatingActionButton(
        shape: const CircleBorder(),
        onPressed: () async {
          data.add('${++counter}');
          // 通知列表更新
          globalKey.currentState!.insertItem(data.length - 1);
          await Future.delayed(const Duration(milliseconds: 300));
          controller.animateTo(
            controller.position.maxScrollExtent,
            duration: const Duration(milliseconds: 100),
            curve: Curves.easeIn,
          );
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget buildItem(BuildContext context, int index) {
    String value = data[index];
    return ListTile(
      key: ValueKey(value),
      title: Text(value),
      trailing: IconButton(
        icon: const Icon(Icons.delete),
        onPressed: () => onDelete(context, index),
      ),
    );
  }

  void onDelete(BuildContext context, int index) {
    setState(() {
      globalKey.currentState!.removeItem(
        index,
            (context, animation) {
          var item = buildItem(context, index);
          data.removeAt(index);
          return FadeTransition(
            opacity: CurvedAnimation(
              parent: animation,
              curve: Curves.easeIn,
            ),
            child: SizeTransition(
              sizeFactor: animation,
              child: item,
            ),
          );
        },
        duration: const Duration(milliseconds: 200),
      );
    });
  }
}
